package aduros.game {

import flash.display.DisplayObject;

import com.whirled.avrg.*;
import com.whirled.net.*;
import com.whirled.game.GameContentEvent;

import com.google.analytics.GATracker;

public class Metrics
{
    public var enabled :Boolean = true;

    public function Metrics (ctrl :AVRGameControl, display :DisplayObject, account :String)
    {
        _ctrl = ctrl;
        _tracker = new GATracker(display, account);

        _ctrl.player.addEventListener(AVRGamePlayerEvent.ENTERED_ROOM, onEnteredRoom);
        _ctrl.player.addEventListener(GameContentEvent.PLAYER_CONTENT_CONSUMED, onContentConsumed);
        _ctrl.player.addEventListener(AVRGamePlayerEvent.TASK_COMPLETED, onTaskCompleted);
        _ctrl.player.addEventListener(MessageReceivedEvent.MESSAGE_RECEIVED, onPlayerMessage);
    }

    public function trackState (name :String) :void
    {
        if (enabled) {
            _tracker.trackPageview(name);
        }
    }

    public function trackEvent (
        category :String, name :String, label :String = null, param :Object = null) :void
    {
        if (enabled) {
            var value :Number = NaN;

            if (param != null) {
                if (param is Number) {
                    // OK, send as normal GA value
                    value = param as Number;
                } else if (param is String) {
                    // GA doesn't support string values, hack it into the event name
                    name += "/" + param;
                } else {
                    throw new ArgumentError("Param must be a Number or String!");
                }
            }

            _tracker.trackEvent(category, name, label, value);
        }
    }

    protected function onEnteredRoom (event :AVRGamePlayerEvent) :void
    {
        var roomId :String = String(event.value);
        trackEvent("Rooms", "entered", _ctrl.room.getRoomName(), roomId);
    }

    protected function onContentConsumed (event :GameContentEvent) :void
    {
        trackEvent("Consumption", event.contentType, null, event.contentIdent);
    }

    protected function onTaskCompleted (event :AVRGamePlayerEvent) :void
    {
        trackEvent("Tasks", event.name, null, event.value);
    }

    protected function onPlayerMessage (event :MessageReceivedEvent) :void
    {
        if (event.name == StatTracker.MESSAGE_TROPHY) {
            trackEvent("Trophies", event.value as String);
        } else if (event.name == StatTracker.MESSAGE_PRIZE) {
            trackEvent("Prizes", event.value as String);
        }
    }

    protected var _tracker :GATracker;
    protected var _ctrl :AVRGameControl;
}

}
